package com.shop.service;

import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.JSON2.json.JSONArray;
import com.JSON2.json.JSONObject;
import com.JSON2.json.JSONTokener;
import com.shop.actionentity.MerchantReg;
import com.shop.dao.MerchantDao;
import com.shop.dao.MerchantInforDao;
import com.shop.daoImpl.AddressDaoImpl;
import com.shop.daoImpl.GoodsDaoImpl;
import com.shop.daoImpl.MerchantAddressDaoImpl;
import com.shop.daoImpl.MerchantOrderDaoImpl;
import com.shop.entity.Address;
import com.shop.entity.Goods;
import com.shop.entity.Merchant;
import com.shop.entity.MerchantAddress;
import com.shop.entity.MerchantInfor;
import com.shop.entity.MerchantMessage;
import com.shop.entity.MerchantOrder;
import com.shop.entity.OrderGoodsList;
import com.shop.entity.OrderLogistics;

/**
 * 
 * <b>商户业务<b>
 * <pre>
 * 负责
 *   注册
 *   登录
 * </pre>
 * @author 威 
 * <br>2018年1月5日 下午2:22:22 
 *
 */
@Service
public class MerchantServiceImpl {
	@Resource(name="merchantDaoImpl")
	private MerchantDao merchantDaoImpl;
	@Resource(name="merchantInforDaoImpl")
	private MerchantInforDao merchantInforDaoImpl;
	@Resource(name="goodsDaoImpl")
	private GoodsDaoImpl goodsDaoImpl;
	@Resource(name="merchantAddressDaoImpl")
	private MerchantAddressDaoImpl merchantAddressDaoImpl;
	@Resource(name="addressDaoImpl")
	private AddressDaoImpl addressDaoImpl;
	@Resource(name="merchantOrderDaoImpl")
	private MerchantOrderDaoImpl merchantOrderDaoImpl;

	public void setMerchantOrderDaoImpl(MerchantOrderDaoImpl merchantOrderDaoImpl) {
		this.merchantOrderDaoImpl = merchantOrderDaoImpl;
	}

	public void setGoodsDaoImpl(GoodsDaoImpl goodsDaoImpl) {
		this.goodsDaoImpl = goodsDaoImpl;
	}

	public void setMerchantDaoImpl(MerchantDao merchantDaoImpl) {
		this.merchantDaoImpl = merchantDaoImpl;
	}

	public void setMerchantInforDaoImpl(MerchantInforDao merchantInforDaoImpl) {
		this.merchantInforDaoImpl = merchantInforDaoImpl;
	}
	public void setMerchantAddressDaoImpl(MerchantAddressDaoImpl merchantAddressDaoImpl) {
		this.merchantAddressDaoImpl = merchantAddressDaoImpl;
	}

	public void setAddressDaoImpl(AddressDaoImpl addressDaoImpl) {
		this.addressDaoImpl = addressDaoImpl;
	}

	/**
	 * 初始化merchant页
	 * 
	 */
	public String initPage(Integer merchantId, String requestCode) {
		System.out.println(merchantId);
		Merchant merchant = merchantDaoImpl.findById(merchantId);
		String trueName = merchant.getMerchantInfor().getTrueName();
		JSONObject object = new JSONObject();
		System.out.println("显示真实姓名的值" + trueName);
		object.put("dearBoss", trueName);
		Object initData = null;
		System.out.println(requestCode);
		String type = "";
		switch(requestCode){
			case "0000" : 
				initData = getOrder(merchant);
				type = "0000";
				break;
			case "0001" : 
				initData = "null";
				type = "0001";
				break;
			case "0003" : 
				initData = getInitInfor(merchant);
				type = "0003";
				break;
			case "0002" : 
				initData = getGoods(merchant);
				type = "0002";
				break;
			default :
				initData = "Data Error";
		}
		object.put("initData", initData);
		object.put("type", type);
		return object.toString();
	}
	/**
	 * 
	 * 二次初始化
	 * @see
	 * @param merchantId
	 * @param requestCode
	 * @return
	 * String
	 *
	 */
	public String nextInitPage(Integer merchantId, String requestCode){
		Merchant merchant = merchantDaoImpl.findById(merchantId);
		String[] temp = {"0000", "0002", "0003"};
		JSONObject object = new JSONObject();
		for(int i = 0; i < temp.length; i++){
			String temp_ = temp[i];
			if(!temp_.equals(requestCode)){
				switch(temp_){
					case "0000" : 
						object.put("orderList", getOrder(merchant));
						break;
					case "0003" : 
						object.put("infor", getInitInfor(merchant));
						break;
					case "0002" : 
						object.put("goodsList", getGoods(merchant));
						break;
					default :
						System.out.println("数据异常");
				}
			}
		}
		return object.toString();
	}
	/**
	 * 
	 * 注册
	 * @see
	 * @param object
	 * void
	 *
	 */
	public void register(MerchantReg object){
		System.out.println("register service...start");
		Merchant m = new Merchant();
		m.setUsername((String) object.getUsername());
		
		m.setPassword((String) object.getPassword());
		MerchantInfor minfor = new MerchantInfor ();
		minfor.setIntegral(0);
		minfor.setName((String) object.getShopName());
		minfor.setPhone_number((String) object.getPhoneNumber());
		minfor.setTrueName(object.getTrueName());
		minfor.setEmail(object.getEmail());
		minfor.setSex(object.getSex());
		minfor.setMerchant(m);
		
		m.setMerchantInfor(minfor);
		System.out.println(merchantDaoImpl);
		System.out.println(merchantInforDaoImpl);
		merchantDaoImpl.save(m);
		merchantInforDaoImpl.save(minfor);
	}
	
	/**
	 * 
	 * 登录
	 * @see
	 * @param username
	 * @param password
	 * @return
	 * boolean
	 *
	 */
	public Object[] login(String username, String password){
		System.out.println("service..." + username + password);
		
		Merchant merchant = merchantDaoImpl.findByUsername(username);
		if(merchant == null){
			System.out.println("当前用户不存在");
			Object[] arr = new Object[]{null, "0001"}; //0001用户不存在
			return arr;
		}
		System.out.println("service...");
		if(merchant.getPassword().equals(password)){
			Object[] arr = new Object[]{merchant.getId(), "0000"};	//0000 密码匹配
			return arr;
		}
		System.out.println("service...");
		Object[] arr = new Object[]{merchant.getId(), "0002"}; 	//0002 密码不匹配
		return arr;
	}
	/**
	 * 
	 * 新增商品
	 * @see
	 * @return
	 * boolean
	 *
	 */
	public boolean addGoods(Integer id,
			String name,
			Double price,
			String size,
			String color,
			String path){
		//当登录之后就会有一个单例的Merchant生成可控之后与商户有关的操作
		Goods goods = new Goods();
		goods.setImgPath("upload/"+path);
		goods.setName(name);
		goods.setPrice(price);
		goods.setSizes(size);
		goods.setColors(color);
		merchantDaoImpl.saveGoods(1, goods);
		return true;
	}
	public Object getGoods(Merchant merchant){
		Set<Goods> gs = merchantDaoImpl.findGoodss(merchant);
		JSONArray arr = new JSONArray();
		JSONObject obj;
		for(Goods g : gs){
			obj = new JSONObject();
			obj.put("id", g.getId());
			obj.put("name", g.getName());
			obj.put("price", g.getPrice());
			obj.put("sizes", g.getSizes());
			obj.put("imgPath", g.getImgPath());
			obj.put("colors", g.getColors());
			arr.add(obj);
		}
		return arr;
	}
	/**
	 * 获取所有商品
	 */
	public String getGoods(Integer id){
		Merchant merchant = merchantDaoImpl.findById(id);
		return getGoods(merchant).toString();
	}
	
	
	public boolean deleGoods(Integer id){
		return goodsDaoImpl.delete(id);
	}
	
	public boolean updateGoods(JSONObject object){
		Goods goods = goodsDaoImpl.findById((Integer) object.get("id"));
		System.out.println(goods.getName());
		
		goods.setColors((String) object.get("colors"));
		goods.setName((String) object.get("name"));
		goods.setPrice((Double) object.get("price"));
		goods.setSizes((String) object.get("sizes")); 
		
		goodsDaoImpl.save(goods);
		return true;
	}
	
	public Object getInitInfor(Merchant merchant){
		MerchantInfor infor = merchant.getMerchantInfor();
		//System.out.println("infor 测试数据 - "+infor.getId());
		Set<MerchantAddress> as = merchant.getMerchantAddress();
		JSONObject object = new JSONObject();
		object.put("mName", infor.getName());
		object.put("integral", infor.getIntegral());
		object.put("trueName", infor.getTrueName());
		object.put("sex", infor.getSex());
		object.put("pNumber", infor.getPhone_number());
		object.put("email", infor.getEmail());
		JSONArray arr = new JSONArray();
		if(as.size() > 0){
			JSONObject addressObject;
			for(MerchantAddress ad : as){
				addressObject = new JSONObject();
				addressObject.put("id", ad.getId());
				addressObject.put("province", ad.getProvince());
				addressObject.put("city", ad.getCity());
				addressObject.put("street", ad.getStreet());
				arr.add(addressObject); 
			}
		}
		object.put("address", arr);
		return object;
	}
	public void updateInfor(Integer merchantId, String jsonStr) throws RuntimeException{
		JSONObject object = (JSONObject) JSONTokener.parseObject(jsonStr);
		Session session = merchantOrderDaoImpl.getSession();
		Merchant merchant = (Merchant) session.get(Merchant.class, merchantId);
		MerchantInfor mInfor = merchant.getMerchantInfor();
		mInfor.setName((String) object.get("storeName"));
		mInfor.setEmail((String) object.get("email"));
		mInfor.setPhone_number((String) object.get("pNumber"));
		mInfor.setSex((String) object.get("sex"));
		mInfor.setTrueName((String) object.get("trueName"));
		
		JSONArray jsonArrObj = (JSONArray) object.get("");
		int len = jsonArrObj.length();
		for(int i = 0; i < len; i++){
			JSONObject jsonObj = jsonArrObj.getJSONObject(i);
			MerchantAddress address = new MerchantAddress();
			if(jsonObj.get("id") != null){
				address.setCity((String) jsonObj.get("province"));
				address.setProvince((String) jsonObj.get("city"));
				address.setStreet((String) jsonObj.get("street"));
			}
			merchant.getMerchantAddress().add(address);
		}
		session.beginTransaction();
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	/**
	 * 
	 * 获取信息
	 * @see
	 * @param id
	 * @return
	 * String
	 *
	 */
	public String getInitInfor(Integer id){
		Merchant merchant = merchantDaoImpl.findById(id);
		//System.out.println("merchant 测试数据 - "+merchant.getId());
		return getInitInfor(merchant).toString();
	}
	/**
	 * 
	 * 获取商品 初始化页面
	 * @see
	 * @param id
	 * @return
	 * String
	 *
	 */
	public String getGoods2(Integer id){
		System.out.println("商户id" + id);
		Merchant merchant = merchantDaoImpl.findById(id);
		System.out.println("step0");
		MerchantInfor info = merchant.getMerchantInfor();
		System.out.println("step0.5");
		String trueName = info.getTrueName();
		System.out.println(trueName);
		Set<Goods> gs = merchant.getGoodss();
		System.out.print("step1");
		JSONObject object = new JSONObject();
		object.put("dearBoss", trueName);
		JSONArray arr = new JSONArray();
		JSONObject obj;
		for(Goods g : gs){
			obj = new JSONObject();
			obj.put("id", g.getId());
			obj.put("name", g.getName());
			obj.put("price", g.getPrice());
			obj.put("imgPath", g.getImgPath());
			arr.add(obj);
		}
		object.put("goodsList", arr);
		System.out.println(object.toString());
		return object.toString();
	}
	/**
	 * 初始化 获取订单 方法的重载
	 */
	public Object getOrder(Merchant merchant){
		Set<MerchantOrder> orders = merchant.getMerchantOrder();
		JSONArray orderArr = new JSONArray();
		for(MerchantOrder order : orders) orderArr.add(getOrderA_Order(merchant, order));
		return orderArr;
	}
	//重载
	public Object getOrder(Merchant merchant, Integer merchantOrderId){
		Set<MerchantOrder> orders = merchant.getMerchantOrder();
		JSONArray orderArr = new JSONArray();
		for(MerchantOrder order : orders){
			if(order.getId() == merchantOrderId){
				orderArr.add(getOrderA_Order(merchant, order));
				break;
			} 
		}
		return orderArr;
	}
	//获取订单处理一些更细的活
	private JSONObject getOrderA_Order(Merchant merchant, MerchantOrder order) {
		JSONObject orderObject = new JSONObject();
		JSONObject obj = new JSONObject();
		obj.put("id", order.getId());
		obj.put("time", order.getTime());
		obj.put("money", order.getTotalAmount());
		orderObject.put("obj", obj); 
		
		JSONObject busi = getBusi_Order(merchant, order); //获取商户信息
		JSONArray goodsArr = getGoods_Order(order); //获取商品
		busi.put("goods", goodsArr);
		orderObject.put("busi", busi);
		return orderObject;
	}
	//获取跟商户有关的信息
	private JSONObject getBusi_Order(Merchant merchant, MerchantOrder order) {
		JSONObject busi = new JSONObject(); 
		MerchantInfor infor = merchant.getMerchantInfor();
		busi.put("storeName", infor.getName());
		busi.put("deliveryState", order.isDeliveryState());
		busi.put("progressState", order.isProgressState());
		
		OrderLogistics orderLogistics = order.getLogistics(); 
		JSONObject logistics = new JSONObject();  System.out.println("getOrder 装入对象2.5");
		if(order.isDeliveryState()){ //确认该订单发货才会有商户发货地址
			Integer merAddressId = orderLogistics.getMerchantAddressId();
			MerchantAddress merchantAddress = merchantAddressDaoImpl.findById(merAddressId); 
			logistics.put("shipAddress", merchantAddress.getProvince() + "-" + merchantAddress.getCity() + "-" + merchantAddress.getStreet());
		}else{
			JSONArray addressArrObj = getShipsAddList_Order(merchant);
			logistics.put("shipAddList", addressArrObj); 
		}
		Integer memAddressId = orderLogistics.getMemeberAddressId();
		Address address_ = addressDaoImpl.findById(memAddressId);
		logistics.put("receiAddress", address_.getProvince() + "-" + address_.getCity() + "-" + address_.getStreet());
		
		busi.put("logistics", logistics); 
		return busi;
	}
	//未发货时所需的供选择的发货地址
	private JSONArray getShipsAddList_Order(Merchant merchant) {
		Set<MerchantAddress> addresss = merchant.getMerchantAddress();
		JSONArray addressArrObj = new JSONArray();
		JSONObject addressObj;
		for(MerchantAddress merchantAddress : addresss){
			addressObj = new JSONObject();
			addressObj.put("id", merchantAddress.getId());
			addressObj.put("text", merchantAddress.getProvince() + 
					" " + merchantAddress.getCity() + 
					" " + merchantAddress.getStreet());
			addressArrObj.add(addressObj);
		}
		return addressArrObj;
	}
	//获取订单商品
	private JSONArray getGoods_Order(MerchantOrder order) {
		JSONArray goodsArr = new JSONArray();
		JSONObject goodsObject;
		Set<OrderGoodsList> gs = order.getOrderGoodsLists();  
		for(OrderGoodsList g : gs){
			goodsObject = new JSONObject();
			Goods goods = goodsDaoImpl.findById(g.getGoods_id());
			goodsObject.put("id", g.getId());
			goodsObject.put("path", goods.getImgPath());
			goodsObject.put("name", goods.getName());
			goodsObject.put("price", goods.getPrice());
			goodsObject.put("size", g.getSize());
			goodsObject.put("color", g.getColor()); System.out.println("getOrder 装入对象5");
			goodsObject.put("count", g.getQuantity());
			System.out.println("goodsObject - "+goodsObject.toString());
			goodsArr.add(goodsObject);
		}
		return goodsArr;
	}
	/**
	 * 初始化 获取订单
	 */
	public String getOrder(Integer id){
		System.out.println("getOrder 开始装入对象");
		String result = getMerchant(id);
		System.out.println("orderArr刷新订单 - " + result);
		return result;
	}

	private String getMerchant(Integer id) {
		Merchant merchant = merchantDaoImpl.findById(id);
		String result = getOrder(merchant).toString();
		return result;
	} 
	/**
	 * 
	 * 商户确认发货
	 * @see
	 * @param merchantOrderId
	 * @return
	 * Boolean
	 *
	 */
	public String sureDeliver(JSONObject object, Integer merchantId) {
		System.out.println("正在进行发货确认");
		Session session = merchantOrderDaoImpl.getSession();
		MerchantOrder merchantOrder = (MerchantOrder) session.get(MerchantOrder.class, (Integer) object.get("id"));
		merchantOrder.setDeliveryState(true);
		OrderLogistics logist = merchantOrder.getLogistics();
		logist.setMerchantAddressId((Integer) object.get("logistId"));
		session.beginTransaction();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return getOrder(merchantDaoImpl.findById(merchantId), merchantOrder.getId()).toString();
	}
	//定时刷新
	public String getNewMessage(Integer merchantId){
		//先判断是否有新信息
		//后解析信息
		//	0000为新的订单
		//最后删除已读取的信息
		Session session = merchantOrderDaoImpl.getSession();
		Merchant merchant = (Merchant) session.get(Merchant.class, merchantId);
		session.beginTransaction();
		Set<MerchantMessage> merchantMessages = merchant.getMerchantMessage();
		JSONObject obj = new JSONObject();
		int len = merchantMessages.size();
		if(len > 0){
			for(MerchantMessage merchantMessage : merchantMessages){
				JSONObject object = (JSONObject) JSONTokener.parseObject(merchantMessage.getMessage());
				if(object.get("type").equals("0000")){
					obj.put("orderList", getOrder(merchant, (Integer) object.get("id")));
					session.delete(merchantMessage);
				}
			}
		}
		session.flush();
		session.getTransaction().commit();
		session.close();
		return obj.toString();
	}
	
}
